package com.yantong.service.impl;

import com.yantong.constant.WxMessageType;
import com.yantong.constant.WxTerminal;
import com.yantong.utils.HttpUtil;
import com.yantong.pojo.WxNotifyParam;
import com.yantong.pojo.wxtemplate.WxSendTemplateNews;
import com.yantong.pojo.wxtemplate.WxSendTextNews;
import com.yantong.service.WxNotifyService;
import com.yantong.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class WxNotifyServiceImpl implements WxNotifyService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WxNotifyServiceImpl.class);
    @Autowired
    private WxService wxService;


    @Override
    public void sendNotify(WxNotifyParam notifyParam) {
        String token = wxService.getAccessToken(notifyParam.getCenterId(), WxTerminal.TERMINAL_GZH.getTerminal());

        try {
            log.info("准备发送消息==="+WxMessageType.MESSAGE_TYPE_NEWS.getType());
            //图文消息发送
            if(WxMessageType.MESSAGE_TYPE_NEWS.getType().equals(notifyParam.getMessageType())){
                log.info("发送图文消息");

                WxSendTextNews news = new WxSendTextNews();
                news.setTouser(notifyParam.getGzhOpenId());
                news.setTitle(notifyParam.getTitle());
                news.setDescription(notifyParam.getContent());
                news.setUrl(notifyParam.getUrl());
                news.setPicUrl(notifyParam.getThumb());
                String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;

                HttpUtil.sendPost(url,news.toTextJSON());

            }
            //文本消息
            else if(WxMessageType.MESSAGE_TYPE_TEXT.getType().equals(notifyParam.getMessageType())){
                log.info("发送文本消息");
                WxSendTextNews news = new WxSendTextNews();
                news.setTouser(notifyParam.getGzhOpenId());
                news.setText(notifyParam.getContent());
                String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;

                HttpUtil.sendPost(url,news.toTextJSON());
            }else if(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType().equals(notifyParam.getMessageType())){
                log.info("发送模板消息");
                WxSendTemplateNews news = new WxSendTemplateNews();
                news.setTouser(notifyParam.getGzhOpenId());
                news.setTemplateId(notifyParam.getTemplateId());
                news.setUrl(notifyParam.getUrl());
                news.setItems(notifyParam.getItems());
                String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
                HttpUtil.sendPost(url,news.toJSON());
            }
        } catch (Exception e) {
            LOGGER.warn("消息推送失败：{}", e.getMessage());
        }
    }


}
